package com.eeepay.eeepay_v2.util;

import android.os.AsyncTask;

import com.eeepay.v2_library.log.LogUtils;

import java.util.concurrent.TimeUnit;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

/**
 * Created by zw on 2016/3/23 0023.
 * Grpc 的异步AsyncTask处理类的基类
 */
public abstract class  BaseGrpcTask<T>  extends AsyncTask<String, String, T> {

    private ManagedChannel mChannel;

    @Override
    protected void onPreExecute() {

    }

    /**
     * 异步操作
     * @param channel
     * @return
     */
    protected abstract T doInBack(ManagedChannel channel);

    /**
     * 更新UI操作
     * @param result
     */
    protected abstract void updateUI(T result);

    @Override
    protected T doInBackground(String... params) {
        try {
            mChannel = ManagedChannelBuilder.forAddress(params[0], Integer.parseInt(params[1]))
                    .usePlaintext(true)
                    .build();
//            mChannel.shutdown().awaitTermination(1, TimeUnit.SECONDS);
            return doInBack(mChannel);
        } catch (Exception e) {
            LogUtils.d("TAG", "back exception = " + e);
            e.printStackTrace();
//            Thread.currentThread().interrupt();
        }
        return null;
    }

    @Override
    protected void onPostExecute(T result) {
        LogUtils.d("TAG", "onPostExecute  result = " + result);
        try {
            mChannel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {

            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
        updateUI(result);
    }

}
